<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */

namespace MoChat\App\Client\Action\Dashboard;

use _PHPStan_b8e553790\Nette\Neon\Exception;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\Rbac\Middleware\PermissionMiddleware;
use MoChat\App\Client\Logic\IndexLogic;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;

/**
 * 客户标签更新
 * @Controller
 */
class ClientGroupLabelUpdate extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class)
     * })
     * @RequestMapping(path="/dashboard/client/groupLabelUpdate", methods="PUT")
     */
    public function handle()
    {
        $user = user();
        if (empty($user)) {
            throw new CommonException(ErrorCode::AUTH_UNAUTHORIZED, '登入异常请重新登入');
        }
        $data = $this->request->all();
        Db::beginTransaction();
        try {
            $groupLabel = Db::table('client_label_group')
                ->where('name', $data['groupName'])
                ->first();
            if (!empty($groupLabel) && $groupLabel->id != $data['id']) {
                throw new CommonException(ErrorCode::SERVER_ERROR, '分组名称已存在');
            }
            Db::table('client_label_group')
                ->where('id', $data['id'])
                ->update([
                    'name' => $data['groupName'],
                    'order' => $data['order']
                ]);
            if (!empty($data['tags'])) {
//                Db::table('client_label')
//                    ->where('client_label_group_id', $data['id'])
//                    ->delete();
                $ids=[];
                foreach ($data['tags'] as $tag) {
                    if (empty($tag['name'])){
                       continue;
                    }
                    $tag['order'] =is_null($tag['order'])?0:$tag['order'];
                    if (isset($tag['id'])){
                        $ids[]=$tag['id'];
                        $t = Db::table('client_label')
                            ->where('client_label_group_id', $data['id'])
                            ->where('id',$tag['id'])
                            ->first();

                        if (empty($t)){
                            Db::table('client_label')
                                ->insert([
                                    'client_label_group_id'=> $data['id'],
                                    'name' => $tag['name'],
                                    'order' => $tag['order']
                                ]);
                        }else  {
                            if ($t->id==$tag['id']){
                                Db::table('client_label')
                                    ->where('id', $tag['id'])
                                    ->update([
                                        'name' => $tag['name'],
                                        'order' => $tag['order']
                                    ]);
                            }else{
                                throw new CommonException(ErrorCode::SERVER_ERROR, '更新标签已存在');
                            }
                        }
                    }else{
                        $t = Db::table('client_label')
                            ->where('name', $tag['name'])
                            ->where('client_label_group_id', $data['id'])
                            ->first();
                        if (empty($t)){
                            $ids[]=Db::table('client_label')
                                ->insertGetId([
                                    'client_label_group_id'=> $data['id'],
                                    'name' => $tag['name'],
                                    'order' => $tag['order']
                                ]);
                        }else{
                            throw new CommonException(ErrorCode::SERVER_ERROR, '新增标签已存在');
                        }
                    }


                }
                if (!empty($ids)){
                    $allIds=Db::table('client_label')
                        ->whereNotIn('id',$ids)
                        ->where('client_label_group_id', $data['id'])
                        ->pluck('id')->toArray();
                    $hasIds=Db::table('client_label_relation')
                        ->whereIn('client_label_id',$allIds)
                        ->pluck('client_label_id')->toArray();
                    $delIds=array_diff($allIds,$hasIds);
                    if (!empty($delIds)){
                        Db::table('client_label')
                            ->whereIn('id',$delIds)
                            ->delete();
                    }
                }
            }
            Db::commit();
        } catch (\Throwable $throwable) {
            Db::rollBack();
            throw new CommonException(ErrorCode::SERVER_ERROR, $throwable->getMessage());
        }
        return [];
    }

    /**
     * 验证规则.
     *
     * @return array 响应数据
     */
    public function rules(): array
    {
        return [
            'groupName' => 'required',
        ];
    }

    /**
     * 获取已定义验证规则的错误消息.
     */
    public function messages(): array
    {
        return [
            'groupName.required' => '分组名称必传',
        ];
    }
}
